<template>
  <doc-alert title="功能权限" url="https://doc.iocoder.cn/resource-permission" />
  <doc-alert title="菜单路由" url="https://doc.iocoder.cn/vue3/route/" />

  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="菜单名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入菜单名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          class="!w-240px"
          clearable
          placeholder="请选择菜单状态"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button
          v-hasPermi="['system:menu:create']"
          plain
          type="primary"
          @click="openForm('create')"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
        <el-button plain type="danger" @click="toggleExpandAll">
          <Icon class="mr-5px" icon="ep:sort" />
          展开/折叠
        </el-button>
        <el-button plain @click="refreshMenu">
          <Icon class="mr-5px" icon="ep:refresh" />
          刷新菜单缓存
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap :bodyStyle="{ height: '700px' }">
    <el-auto-resizer>
      <template #default="{ height, width }">
        <el-table-v2
          :columns="columns"
          expand-column-key="name"
          :data="list"
          :width="width"
          :height="700"
        >
          <template #cell="{ column, rowData }">
            <template v-if="column.dataKey === 'icon'">
              <Icon :icon="rowData.icon" />
            </template>
            <template v-else-if="column.dataKey === 'status'">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="rowData.status" />
            </template>
            <template v-else-if="column.dataKey === 'visible'">
              <dict-tag :type="DICT_TYPE.COMMON_VISIBLE" :value="rowData.visible" />
            </template>
            <template v-else-if="column.dataKey === 'operation'">
              <el-button
                v-hasPermi="['system:menu:update']"
                link
                type="primary"
                @click="openForm('update', rowData.id)"
              >
                修改
              </el-button>
              <el-button
                v-hasPermi="['system:menu:create']"
                link
                type="primary"
                @click="openForm('create', undefined, rowData.id)"
              >
                新增
              </el-button>
              <el-button
                v-hasPermi="['system:menu:delete']"
                link
                type="danger"
                @click="handleDelete(rowData.id)"
              >
                删除
              </el-button>
              <el-dropdown
                @command="(command) => handleCommand(command, rowData)"
                v-hasPermi="[
                  'system:user:delete',
                  'system:user:update-password',
                  'system:permission:assign-user-role'
                ]"
              >
                <el-button type="primary" link><Icon icon="ep:d-arrow-right" /> 更多</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      command="handleMenuDisable"
                      v-if="checkPermi(['system:menu:update'])"
                    >
                      <Icon icon="ep:delete" />禁用
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="handleMenuDisableAll"
                      v-if="checkPermi(['system:menu:update'])"
                    >
                      <Icon icon="ep:delete" />禁用含子菜单
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="handleMenuEnable"
                      v-if="checkPermi(['system:menu:update'])"
                    >
                      <Icon icon="ep:delete" />启用
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="handleMenuEnableAll"
                      v-if="checkPermi(['system:menu:update'])"
                    >
                      <Icon icon="ep:delete" />启用含子菜单
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <template v-else>
              {{ rowData[column.dataKey] }}
            </template>
          </template>
        </el-table-v2>
      </template>
    </el-auto-resizer>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MenuForm ref="formRef" @success="getList" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { handleTree } from '@/utils/tree'
import * as MenuApi from '@/api/system/menu'
import MenuForm from './MenuForm.vue'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { updateAllStatusMenu } from '@/api/system/menu'
import { checkPermi } from '@/utils/permission'
import * as UserApi from '@/api/system/user'
import { Column } from 'element-plus'

const stringify = JSON.stringify

defineOptions({ name: 'SystemMenu' })

const { wsCache } = useCache()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const list = ref<any>([]) // 列表的数据
const queryParams = reactive({
  name: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const isExpandAll = ref(false) // 是否展开，默认全部折叠
const refreshTable = ref(true) // 重新渲染表格状态

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MenuApi.getMenuList(queryParams)
    list.value = handleTree(data)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number, parentId?: number) => {
  formRef.value.open(type, id, parentId)
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 刷新菜单缓存按钮操作 */
const refreshMenu = async () => {
  try {
    await message.confirm('即将更新缓存刷新浏览器！', '刷新菜单缓存')
    // 清空，从而触发刷新
    wsCache.delete(CACHE_KEY.USER)
    wsCache.delete(CACHE_KEY.ROLE_ROUTERS)
    // 刷新浏览器
    location.reload()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MenuApi.deleteMenu(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 操作分发 */
const handleCommand = (command: string, row: any) => {
  switch (command) {
    case 'handleMenuDisable':
      handleMenuDisable(row.id)
      break
    case 'handleMenuDisableAll':
      handleMenuDisableAll(row.id)
      break
    case 'handleMenuEnable':
      handleMenuEnable(row.id)
      break
    case 'handleMenuEnableAll':
      handleMenuEnableAll(row.id)
      break
    default:
      break
  }
}

const handleMenuDisable = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm('是否确认禁用', '提示')
    // 发起删除
    await MenuApi.updateAllStatusMenu({ id, withChild: false, status: 1 })
    message.success(t('禁用成功'))
    // 刷新列表
    await getList()
  } catch {}
}

const handleMenuDisableAll = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm('是否确认禁用', '提示')
    // 发起删除
    await MenuApi.updateAllStatusMenu({ id, withChild: true, status: 1 })
    message.success(t('禁用成功'))
    // 刷新列表
    await getList()
  } catch {}
}

const handleMenuEnable = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm('是否确认启用', '提示')
    // 发起删除
    await MenuApi.updateAllStatusMenu({ id, withChild: false, status: 0 })
    message.success(t('启用成功'))
    // 刷新列表
    await getList()
  } catch {}
}

const handleMenuEnableAll = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm('是否确认启用', '提示')
    // 发起删除
    await MenuApi.updateAllStatusMenu({ id, withChild: true, status: 0 })
    message.success(t('启用成功'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getList()
})

//
const columns: Column<any>[] = [
  {
    title: '菜单名称',
    key: 'name',
    dataKey: 'name',
    width: 300
  },
  {
    title: '图标',
    key: 'icon',
    dataKey: 'icon',
    width: 100
  },
  {
    title: '排序',
    key: 'sort',
    dataKey: 'sort',
    width: 70
  },
  {
    title: '权限标识',
    key: 'permission',
    dataKey: 'permission',
    width: 150
  },
  {
    title: '组件路径',
    key: 'component',
    dataKey: 'component',
    width: 150
  },
  {
    title: '组件名称',
    key: 'componentName',
    dataKey: 'componentName',
    width: 150
  },
  {
    title: '状态',
    key: 'status',
    dataKey: 'status',
    width: 100
  },
  {
    title: '显示状态',
    key: 'visible',
    dataKey: 'visible',
    width: 100
  },
  {
    title: '操作',
    key: 'operation',
    dataKey: 'operation',
    width: 200
  }
]
</script>
